package com.example.nophase;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.nophase.Fragment.FinanceHomeContentFragment;
import com.example.nophase.Fragment.ManagerHomeContentFragment;
import com.example.nophase.Fragment.StaffMainHomeContentFragment;
import com.example.nophase.Fragment.WageGroupHomeContentFragment;
import com.example.nophase.activity.staff.AreaProjectActivity;
import com.example.nophase.activity.staff.ProjectActivity;
import com.example.nophase.api.RequstCommonApi;
import com.example.nophase.base.BaseActivity;
import com.example.nophase.common.BaseCallBack;
import com.example.nophase.common.BaseResp;
import com.example.nophase.common.LoginManager;
import com.example.nophase.common.MyActivityManager;
import com.example.nophase.common.OnNetworkAccessToMessageListener;
import com.example.nophase.config.Configuration;
import com.example.nophase.custom.CustomDialog;
import com.example.nophase.custom.InputDialog;
import com.example.nophase.entity.SysUserVO;
import com.example.nophase.entity.UpdatePassword;
import com.example.nophase.entity.Version;
import com.example.nophase.utils.HttpUtils;
import com.example.nophase.utils.SPUtils;
import com.example.nophase.utils.Sha1Utils;

import com.example.nophase.utils.UpdateManager;
import com.igexin.sdk.PushManager;
import com.taobao.sophix.SophixManager;
import com.tbruyelle.rxpermissions2.RxPermissions;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

public class HomeActivity extends BaseActivity {
    RxPermissions rxPermissions;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.home_content)
    LinearLayout homeContent;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.toolbar_btn)
    Button toolbarBtn;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.user_account)
    TextView userAccount;
    @BindView(R.id.user_tel)
    TextView userTel;
    @BindView(R.id.user_position)
    TextView userPosition;
    @BindView(R.id.exit_btn)
    Button exitBtn;
    @BindView(R.id.user_rols)
    TextView userRols;
    @BindView(R.id.update_password)
    LinearLayout updatePassword;
    @BindView(R.id.close_drawer_iv)
    ImageView closeDrawerIv;

    private FragmentTransaction transaction;
    private SysUserVO userVO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        setToolbar();
        transparencyBar(HomeActivity.this);
        userVO = LoginManager.getUserInfo(HomeActivity.this);
        userName.setText(userVO.getUsername());
        userAccount.setText(userVO.getAccount());
        userPosition.setText(userVO.getMoreInfo().getPosition());
        userRols.setText(userVO.getMoreInfo().getPosition());
        userTel.setText(userVO.getPhone());
        updatePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPassword();
            }
        });
        closeDrawerIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }
        });
        FragmentManager manager = getSupportFragmentManager();//初始化FragmentManager，获取v4包所支持的fragment

        //初始化FragmentTransaction
        transaction = manager.beginTransaction();


        switch (userVO.getMoreInfo().getPosition()) {
            case "区域业务员":
                transaction.
                        add(R.id.content_fragment,
                                StaffMainHomeContentFragment.newInstance(HomeActivity.this)).commit();
                break;
            case "职能中心员工":

                transaction.
                        add(R.id.content_fragment,
                                StaffMainHomeContentFragment.newInstance(HomeActivity.this)).commit();
                break;
            case "总公司财务":
                transaction.
                        add(R.id.content_fragment,
                                FinanceHomeContentFragment.newInstance(HomeActivity.this)).commit();
                toolbarBtn.setVisibility(View.GONE);
                break;
            case"总公司工资组组员":
                transaction.
                        add(R.id.content_fragment,
                                WageGroupHomeContentFragment.newInstance(HomeActivity.this)).commit();
                toolbarBtn.setVisibility(View.GONE);
                break;
            default:
                toolbarBtn.setVisibility(View.GONE);
                transaction.
                        add(R.id.content_fragment,
                                ManagerHomeContentFragment.newInstance(HomeActivity.this)).commit();

                break;
        }


        rxPermissions = new RxPermissions(this);
        /**
         * 权限判断
         */
        rxPermissions.request(
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE


        )
                .subscribe(granted -> {
                    if (granted) {
                        Log.e("==", "权限成功!");
                        start();
                    } else {
                        finish();
                    }
                });
        SophixManager.getInstance().queryAndLoadNewPatch();


        UpdateManager updateManager = new UpdateManager(this);
        //       int code = updateManager.getVersion();
        //      System.out.println("code=========" + code);
        //updateManager.checkUpdateInfo();
        Call<BaseResp<Version>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadAppVesion("ANDROID", 1);
        call.enqueue(new BaseCallBack<BaseResp<Version>>() {
            @Override
            public void onSuccess(Response<BaseResp<Version>> response) throws Exception {

                String androidVersion = response.body().getData().getAndroidVersion();
                if (getVersion() < Integer.valueOf(androidVersion)) {

                    CustomDialog customDialog=new CustomDialog(HomeActivity.this,"系统更新","系统有新的版本，是否更新","是","否");
                    customDialog.show();
                    customDialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            customDialog.dismiss();
                            updateManager.checkUpdateInfo();
                        }

                        @Override
                        public void doCancel() {
                            customDialog.dismiss();
                        }
                    });

                }

            }

            @Override
            public void onFailure(String message) {

            }
        });

    }

    public int getVersion() {
        PackageInfo pkg;
        int versionCode = 0;
        String versionName = "";
        try {
            pkg = HomeActivity.this.getPackageManager().getPackageInfo(HomeActivity.this.getApplication().getPackageName(), 0);
            versionCode = pkg.versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return versionCode;

    }

    public void showPassword() {
        InputDialog dialog = new InputDialog(HomeActivity.this, "密码", "确认", "取消");
        dialog.show();
        dialog.setHint("请输入修改的密码");
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {

                String password = dialog.getInputMsg();
                update(password);
                dialog.dismiss();

            }

            @Override
            public void doCancel() {
                dialog.dismiss();
            }
        });
    }

    public void update(String newPassword) {
        UpdatePassword updatePassword = new UpdatePassword();
        String oldpassword = (String) SPUtils.get(HomeActivity.this, "password", "");
        updatePassword.setOldPassword(Sha1Utils.encry(oldpassword));
        updatePassword.setNewPassword(Sha1Utils.encry(newPassword));
        updatePassword.setConfirmPassword(Sha1Utils.encry(newPassword));
        Call<BaseResp<Object>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).updataPassword("ADNROID", updatePassword);
        call.enqueue(new BaseCallBack<BaseResp<Object>>() {
            @Override
            public void onSuccess(Response<BaseResp<Object>> response) throws Exception {

                System.out.println("=======" + response.body().toString());
                String code = response.body().getCode();
                boolean success = response.body().getSuccess();
                if (code.equals("200") && success) {
                    Toast.makeText(HomeActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    MyActivityManager.finishAll();
                }
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    @TargetApi(19)
    public static void transparencyBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    private void start() {
        //模拟登陆成功后, 绑定别名和ns
        Log.e("==", "绑定别名成功!");
        SysUserVO sysUserVO = LoginManager.getUserInfo(HomeActivity.this);
        String uuid = sysUserVO.getUuid();
        PushManager.getInstance().bindAlias(HomeActivity.this, uuid);
    }


    private void setToolbar() {
        toolbar.setNavigationIcon(R.drawable.ic_format_align_justify_black_24dp);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
            toolbar.getBackground().setAlpha(255);
        }
        toolbarBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (userVO.getMoreInfo().getPosition()) {
                    case "区域业务员":
                        startActivity(new Intent(HomeActivity.this, AreaProjectActivity.class));
                        break;
                    case "区域项目负责人":
                        startActivity(new Intent(HomeActivity.this, AreaProjectActivity.class));
                        break;
                    case "职能中心员工":

                        startActivity(new Intent(HomeActivity.this, ProjectActivity.class));
                        break;
                    case "总公司财务":
                        startActivity(new Intent(HomeActivity.this, ProjectActivity.class));
                        break;

                    default:
                        startActivity(new Intent(HomeActivity.this, ProjectActivity.class));

                        break;


                }

            }
        });
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                drawerLayout.openDrawer(GravityCompat.START);
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick(R.id.exit_btn)
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.exit_btn:
                MyActivityManager.finishAll();
                break;
        }


    }


}
